package com.inhim.pjhim.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.adapter.DialogFoundRecViewAdapter;
import com.inhim.pjhim.adapter.TagReaderListAdapter;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.base.ClassicsHeader;
import com.inhim.pjhim.entity.ReaderTagList;
import com.inhim.pjhim.entity.ReaderTwo;
import com.inhim.pjhim.entity.ReaderTypeList;
import com.inhim.pjhim.entity.TagReaderList;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.RecylerViewUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;

import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import okhttp3.Request;

public class FoundFragment extends Fragment {
    private RecyclerView ycRefreshView;
    private SmartRefreshLayout home_SwipeRefreshLayout;
    private ReaderTypeList.List ReaderType;
    private List<ReaderTagList.List> mReaderTypeList;
    private List mMainReaderTypeList;
    private TagReaderListAdapter mAdapter;
    private int mPageNum=1;
    private int mMainPageNum=1;
    private Boolean refresh=true;
    private Boolean mainRefresh=true;
    private int totalPage;
    private int mainTotalPage;
    private Gson gson;
    private TextView tv_title;
    private ImageView iv_back;
    private int mAdapterPsition;
    private LinearLayout lin_dialog;
    private RecyclerView recy_top_type;
    private View background_dialog;
    private DialogFoundRecViewAdapter mDialogRecViewAdapter;
    private Activity mContext;
    private String mType;
    private int mReaderTypeId;
    private LinearLayout top_background;
    private List<ReaderTagList.List> removewList;
    private TextView tv_all_type;
    private int mId;
    private View statusBar;
    private int mSclectPosition;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_found, container, false);
        mMainReaderTypeList=new ArrayList();
        mType="2";
        mReaderTypeId=0;
        mContext=getActivity();
        gson=new Gson();
        initView(view);
        return view;
    }

    @SuppressLint("NewApi")
    private void initView(View view) {
        statusBar = view.findViewById(R.id.statusBarView);
        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
        layoutParams.height = MyApplication.getStatusBarHeight();
        tv_all_type=view.findViewById(R.id.tv_all_type);
        top_background=view.findViewById(R.id.top_background);
        ycRefreshView=view.findViewById(R.id.ycRefreshView);
        iv_back=view.findViewById(R.id.iv_back);
        tv_title=view.findViewById(R.id.tvCourse);
        lin_dialog=view.findViewById(R.id.lin_dialog);
        recy_top_type=view.findViewById(R.id.recy_top_type);
        //tv_dialog_name.setText(Title+"分类");
        background_dialog=view.findViewById(R.id.background_dialog);
        background_dialog.setBackgroundColor(Color.BLACK);
        background_dialog.getBackground().setAlpha(50);
        background_dialog.setOnClickListener(v -> {
            //lin_dialog.setVisibility(View.GONE);
            tv_all_type.setVisibility(View.GONE);
            background_dialog.setVisibility(View.GONE);
            mainRefresh=true;
            mDialogRecViewAdapter.clear();
            mDialogRecViewAdapter.addAll(removewList);
            mDialogRecViewAdapter.setShowAllView(true,0);
            mDialogRecViewAdapter.notfyPosition(mSclectPosition);
            setTopBackgroundHeight(true);
        });
        /*tv_all_type.setOnClickListener(v -> {
            mDialogRecViewAdapter.clear();
            mDialogRecViewAdapter.addAll(removewList);
            mDialogRecViewAdapter.setShowAllView(true,0);
            mDialogRecViewAdapter.notifyDataSetChanged();
            setTopBackgroundHeight(true);
            tv_all_type.setVisibility(View.GONE);
        });*/
        tv_title.setText("发现");
        initAdapter(view);
        getReaderTypeList();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initAdapter(View view) {
        mAdapter = new TagReaderListAdapter(mMainReaderTypeList, mContext);
        ycRefreshView.setLayoutManager(new LinearLayoutManager(mContext));
        ycRefreshView.setAdapter(mAdapter);
        home_SwipeRefreshLayout = view.findViewById(R.id.home_SwipeRefreshLayout);
        home_SwipeRefreshLayout.setOnRefreshListener(refreshlayout -> {
            mPageNum= 1;
            refresh=true;
            getMainReaderTypeList(mId);
            home_SwipeRefreshLayout.finishRefresh();
        });
        home_SwipeRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            //加载
            home_SwipeRefreshLayout.finishLoadmore();      //加载完成
            mPageNum++;
            refresh = false;
            getMainReaderTypeList(mId);
            home_SwipeRefreshLayout.finishRefresh();
        });
        /**
         * 设置不同的头部、底部样式
         */
        home_SwipeRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        home_SwipeRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        /*mAdapter.setOnItemClickListener(position -> {
            ReaderTypeList.List reader=mAdapter.getAllData().get(position);
            Intent intent=new Intent(mContext, ProjectListActivity.class);
            //intent.putExtra("TAG",TAG);
            intent.putExtra("ReaderTypeList",reader);
            startActivity(intent);
        });*/

        mDialogRecViewAdapter=new DialogFoundRecViewAdapter(mContext);
        recy_top_type.setAdapter(mDialogRecViewAdapter);
        recy_top_type.scrollToPosition(mAdapterPsition);
        mDialogRecViewAdapter.setItemOnClickListener(position -> {
            String name=mContext.getResources().getString(R.string.see_all);
            if(removewList!=null&&mDialogRecViewAdapter.getShowAllView()&&removewList.get(position).getName().equals(name)){
                mDialogRecViewAdapter.clear();
                mDialogRecViewAdapter.addAll(mReaderTypeList);
                mDialogRecViewAdapter.setShowAllView(false,0);
                mDialogRecViewAdapter.notfyPosition(mSclectPosition);
                setTopBackgroundHeight(false);
                tv_all_type.setVisibility(View.VISIBLE);
                background_dialog.setVisibility(View.VISIBLE);
                mainRefresh=false;
            }else{
                mSclectPosition=position;
                tv_all_type.setVisibility(View.GONE);
                background_dialog.setVisibility(View.GONE);
                ReaderTagList.List serachList=mDialogRecViewAdapter.getAllData().get(position);
                mainRefresh=true;
                mId=serachList.getId();
                getMainReaderTypeList(mId);
                mDialogRecViewAdapter.clear();
                mDialogRecViewAdapter.addAll(removewList);
                mDialogRecViewAdapter.setShowAllView(true,0);
                mDialogRecViewAdapter.notfyPosition(position);
                setTopBackgroundHeight(true);
            }
        });

    }

    private void getReaderTypeList(){
        HashMap postMap=new HashMap();
        String url=Urls.getReaderTagList(1, 100);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url,postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                getMainReaderTypeList(mId);
            }

            @Override
            public void onSuccess(Request request, String result) {
                try{
                    ReaderTagList readerLists = gson.fromJson(result, ReaderTagList.class);
                    if(readerLists.getCode()==0){
                        mReaderTypeList=readerLists.getPage().getList();
                        totalPage=readerLists.getPage().getTotalPage();
                        if(refresh){
                            mMainReaderTypeList.clear();
                        }
                        if(mReaderTypeList.size()>=3){
                            removewList=new ArrayList<>();
                            for (Iterator<ReaderTagList.List> iter = mReaderTypeList.listIterator(); iter.hasNext(); ) {
                                ReaderTagList.List type = iter.next();
                                removewList.add(type);
                                if(removewList.size()==10){
                                    ReaderTagList.List allName=new ReaderTagList.List();
                                    allName.setName(mContext.getResources().getString(R.string.see_all));
                                    removewList.add(allName);
                                    break;
                                }
                            }
                            mDialogRecViewAdapter.addAll(removewList);
                            mDialogRecViewAdapter.setShowAllView(true,0);
                            mDialogRecViewAdapter.notifyDataSetChanged();
                            setTopBackgroundHeight(true);
                            tv_all_type.setVisibility(View.GONE);
                        }else{
                            mDialogRecViewAdapter.addAll(mReaderTypeList);
                            mDialogRecViewAdapter.setShowAllView(false,0);
                            mDialogRecViewAdapter.notifyDataSetChanged();
                            setTopBackgroundHeight(false);
                            tv_all_type.setVisibility(View.VISIBLE);
                        }
                        RecylerViewUtils.attachGridLayoutRv(mContext,recy_top_type,RecylerViewUtils.UNSET_GRID);
                        mId=mReaderTypeList.get(0).getId();
                    }
                    getMainReaderTypeList(mId);
                }catch (Exception e){
                    getMainReaderTypeList(mId);
                    e.printStackTrace();
                }
            }
        });
    }

    private void getMainReaderTypeList(int id){
        HashMap postMap=new HashMap();
        long time=System.currentTimeMillis();
        //String url=Urls.getReaderTypeList(mMainPageNum, 8, type,ReaderTypeId);
        String url=Urls.getTagReaderList(id, mPageNum, 5);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url,postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                Log.d("zhiqiang","IOException");
            }

            @Override
            public void onSuccess(Request request, String result) {
                try{
                    Log.d("zhiqiang","time1:"+(System.currentTimeMillis()-time));
                    TagReaderList tagReaderList = gson.fromJson(result, TagReaderList.class);
                    if(refresh){
                        mMainReaderTypeList.clear();
                    }
                    for (int i = 0; i < tagReaderList.getPage().getList().size(); i++) {
                        TagReaderList.ReaderType mReader = tagReaderList.getPage().getList().get(i).getReaderType();
                        if (tagReaderList.getPage().getList().get(i).getReaderType() != null) {
                            ReaderTwo readerTwo = new ReaderTwo();
                            readerTwo.setSynopsis(mReader.getSynopsis());
                            readerTwo.setAuthorId(mReader.getAuthorId());
                            readerTwo.setType(mReader.getType());
                            readerTwo.setTagName(mReader.getTagName());
                            readerTwo.setTagIds(mReader.getTagIds());
                            readerTwo.setReaderTypeId(mReader.getReaderTypeId());
                            readerTwo.setCreateTime(mReader.getCreateTime());
                            readerTwo.setDoubSort(mReader.getDoubSort());
                            readerTwo.setIcon(mReader.getIcon());
                            readerTwo.setIsShow(mReader.getIsShow());
                            readerTwo.setReadAmount(mReader.getReadAmount());
                            readerTwo.setLevel(mReader.getLevel());
                            readerTwo.setReaderTypeId(mReader.getReaderTypeId());
                            readerTwo.setName(mReader.getName());
                            readerTwo.setOpen(mReader.getOpen());
                            readerTwo.setParentIdLink(mReader.getParentIdLink());
                            readerTwo.setParentName(mReader.getParentName());
                            readerTwo.setPyFull(mReader.getPyFull());
                            readerTwo.setPyShort(mReader.getPyShort());
                            readerTwo.setReadAmount(mReader.getReadAmount());
                            readerTwo.setTotal(mReader.getTotal());
                            readerTwo.setUpdateTime(mReader.getUpdateTime());
                            readerTwo.setUpdateTime(mReader.getUpdateTime());
                            mMainReaderTypeList.add(readerTwo);
                        }
                    }
                    for (int i = 0; i < tagReaderList.getPage().getList().size(); i++) {
                        TagReaderList.Reader mReader1 = tagReaderList.getPage().getList().get(i).getReader();
                        if (mReader1 != null) {
                            mMainReaderTypeList.add(mReader1);
                        }
                    }
                    /*if (tagReaderList.getCode() == 0) {
                        mAdapter.notifyDataSetChanged();
                    }*/
                    mAdapter.notifyDataSetChanged();
                    Log.d("zhiqiang","time2:"+(System.currentTimeMillis()-time));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    private void setTopBackgroundHeight(boolean isAllShow){
        ViewTreeObserver vto = recy_top_type.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        recy_top_type.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                        int bottomHeight = recy_top_type.getHeight()+ mContext.getResources().getDimensionPixelSize(R.dimen.base_dimen_60);

                        int bottomMeasuredHeight = recy_top_type.getMeasuredHeight();

                        RelativeLayout.LayoutParams Params;

                        if(isAllShow){
                            Params =  (RelativeLayout.LayoutParams)top_background.getLayoutParams();
                            Params.height = bottomHeight+statusBar.getHeight();
                            top_background.setBackgroundResource(R.mipmap.background_rec_type);
                        }else{
                            Params =  (RelativeLayout.LayoutParams)top_background.getLayoutParams();
                            Params.height = bottomHeight+tv_all_type.getHeight()+mContext.getResources().getDimensionPixelSize(R.dimen.base_dimen_0)+statusBar.getHeight();;
                            top_background.setBackgroundResource(R.mipmap.background_rec_type_all);
                        }
                        top_background.setLayoutParams(Params);
                    }
                });
    }
}
